package linuxbox.poll.bean;

import java.util.*;

import linuxbox.exception.*;
import linuxbox.bean.*;
import linuxbox.util.*;

import linuxbox.poll.logic.BoxPollEntry;

public class BoxPollEntryBean extends BoxPollEntry implements ITableBean
{
  protected DbAdapter m_db = null;
  protected boolean m_bTransaction = false;
  static protected String m_TableName = "box_poll";

  public BoxPollEntryBean(BaseIntKey pk, DbAdapter db)
  {
    this.init(pk, db);
  }

  public BoxPollEntryBean(BaseIntKey pk)
  {
    this.init(pk, null);
  }

  public void init(BaseIntKey pk, DbAdapter db)
  {
    if (db != null)
    {
      m_db = db;
      m_bTransaction = true;
    }
    if (pk != null)
      setID(pk.getID());
  }

  public String getTableName()
  {
    return m_TableName;
  }

  public void setTableName(String str)
  {
    m_TableName = str;
  }

  public void makeConnection() throws Exception
  {
    if ( m_db == null )
      m_db = new DbAdapter(true);
  }

  public void closeConnection() throws Exception
  {
    if (m_db != null)
    {
      m_db.close();
      m_db = null;
    }
  }

  public void load() throws Exception
  {
    StringBuffer sql = new StringBuffer();

    sql.append("select id, subject, description, multiple, showvoter, concludetime, createtime, createdby, showresult, manualconclude, sendresult, closed from ");
    sql.append(getTableName());
    sql.append(" where id = " + getID());

    makeConnection();
    m_db.executeQuery(sql.toString());
    if (m_db.next())
    {
      m_iID = m_db.getInt(1);                     //id
      m_sSubject = m_db.getString(2);             //subject
      m_sDescription = m_db.getString(3);         //description
      m_bMultiple = (m_db.getInt(4) != 0);        //multiple
      m_bShowVoter = (m_db.getInt(5) != 0);       //showvoter
      m_ConcludeTime = m_db.getTimestamp(6);      //concludetime
      m_CreateTime = m_db.getTimestamp(7);        //createtime
      m_CreatedBy = m_db.getInt(8);           //createdby
      m_bShowResult = (m_db.getInt(9) != 0);      //showresult
      m_bManualConclude = (m_db.getInt(10) != 0); //manualconclude
      m_iSendResult = m_db.getInt(11);            //sendresult
      m_bClosed = (m_db.getInt(12)!=0);            //sendresult
    }
    else
    {
      if (!m_bTransaction)
        closeConnection();
      throw new LinuxboxException(ExceptionHelper.POLL, "LOAD", "Load error:  m_iID=" + m_iID);
    }
    if (!m_bTransaction)
      closeConnection();
  }

  public void store() throws Exception
  {
    StringBuffer sql = new StringBuffer();
    sql.append("UPDATE ");
    sql.append(getTableName());
    sql.append(" set ");
    DBUtil.setInteger(sql, "multiple", ((m_bMultiple)?1:0), true);
    DBUtil.setInteger(sql, "showresult", ((m_bShowResult)?1:0), false);
    DBUtil.setInteger(sql, "manualconclude", ((m_bManualConclude)?1:0), false);
    DBUtil.setInteger(sql, "closed", ((m_bClosed)?1:0), false);
    DBUtil.setInteger(sql, "sendresult", m_iSendResult, false);
    DBUtil.setInteger(sql, "showvoter", ((m_bShowVoter)?1:0), false);
    DBUtil.setString(sql, "subject", m_sSubject, false);
    DBUtil.setString(sql, "description", m_sDescription, false);
    DBUtil.setInteger(sql, "createdby", m_CreatedBy, false);
    DBUtil.setTimestamp(sql, "createtime", m_CreateTime, false);
    DBUtil.setTimestamp(sql, "concludetime", m_ConcludeTime, false);

    sql.append(" where id = " + m_iID);

    makeConnection();
    m_db.executeUpdate(sql.toString());
    if (!m_bTransaction)
      closeConnection();
  }

  public void refresh() throws Exception
  {
    load();
  }

  public void create() throws Exception
  {
    if (m_iID != 0)
    {
      String sql = "INSERT INTO ";
      sql += getTableName();
      sql += " (id) VALUES(" + m_iID + ")";
      makeConnection();
      m_db.executeUpdate(sql);
    }
    else
    {
      String sql = "select max(id) from ";
      sql += getTableName();
      makeConnection();
      m_db.executeQuery(sql);
      int max_id = 0;
      if (m_db.next())
      {
        max_id = m_db.getInt(1);
      }
      max_id++;
      m_iID = max_id;
      sql = "insert into ";
      sql += getTableName();
      sql += " (id) values(" + max_id + ")";
      m_db.executeUpdate(sql);
    }
    if (!m_bTransaction)
      closeConnection();
  }

  public void remove() throws Exception
  {
    String sql = "DELETE FROM ";
    sql += getTableName();
    sql += (" where id = " + m_iID);
    makeConnection();
    m_db.executeUpdate(sql);
    if (!m_bTransaction)
      closeConnection();
  }

  public Object findByKey() throws Exception
  {
    String sql = "select id from ";
    sql += getTableName();
    sql += (" where id = " + m_iID);
    makeConnection();
    m_db.executeQuery(sql);
    BaseIntKey pk = null;
    if(m_db.next())
    {
      pk = new BaseIntKey();
      pk.setID(m_db.getInt(1));
    }
    if (!m_bTransaction)
      closeConnection();
    return pk;
  }

  public int getCount(String sql) throws Exception
  {
    int count = 0;
    try
    {
      makeConnection();
      m_db.executeQuery(sql);
      if (m_db.next())
        count = m_db.getInt(1);
      if (!m_bTransaction)
        closeConnection();
    }
    catch(Exception e)
    {
      if (!m_bTransaction)
        closeConnection();
      throw new LinuxboxException(ExceptionHelper.POLL, "findBySql", "Can't find record: " + e.getMessage());
    }
    return count;
  }

  public Iterator findBySql(String sqlWhere)	throws Exception
  {
    Vector v = null;
    try
    {
      String sql = "select id from ";
      sql += getTableName();
      sql += sqlWhere;
      makeConnection();
      m_db.executeQuery(sql);
      BaseIntKey pk = null;
      v = new Vector();
      while (m_db.next())
      {
        pk = new BaseIntKey();
        pk.setID(m_db.getInt(1));
        v.addElement(pk);
      }
      if (!m_bTransaction)
        closeConnection();
    }
    catch(Exception e)
    {
      if (!m_bTransaction)
        closeConnection();
      throw new LinuxboxException(ExceptionHelper.POLL, "findBySql", "Can't find record: " + e.getMessage());
    }
    return v.iterator();
  }

  public boolean updateBySql(String sql)	throws Exception
  {
    try
    {
      makeConnection();
      m_db.executeUpdate(sql);
      if (!m_bTransaction)
        closeConnection();
    }
    catch(Exception e)
    {
      if (!m_bTransaction)
        closeConnection();
      throw new LinuxboxException(ExceptionHelper.POLL, "updateBySql", "Can't update: " + e.getMessage());
    }
    return true;
  }

  public int getCountBySql(String sqlWhere) throws Exception
  {
    int count = 0;
    try
    {
      StringBuffer sql = new StringBuffer();
      sql.append("select count(id) from ");
      sql.append(getTableName());
      sql.append(sqlWhere);

      makeConnection();
      m_db.executeQuery(sql.toString());
      if (m_db.next())
        count = m_db.getInt(1);
      if (!m_bTransaction)
        closeConnection();
    }
    catch(Exception e)
    {
      if (!m_bTransaction)
        closeConnection();
      throw new LinuxboxException(ExceptionHelper.POLL, "getCountBySql", "Can't find record: " + e.getMessage());
    }
    return count;
  }

}
